package ch8;

import java.util.Random;

public class Example8_23 {
    public static void main(String args[]) {
        RedEnvelope redEnvelope = new RandomRedEnvelope(5.20,6);
        System.out.printf("以下用循环输出%d个人抢%.2f元的随机红包:\n",
                redEnvelope.remainPeople,redEnvelope.remainMoney);
        showProcess(redEnvelope);
    }
    public static void showProcess (RedEnvelope redEnvelope) {
        double sum = 0;
        while(redEnvelope.remainPeople>0){
            double money = redEnvelope.giveMoney();
            System.out.printf("%.2f\t",money);
            sum = sum+money;
        }
        String s = String.format("%.2f",sum);
        sum = Double.parseDouble(s);
        System.out.printf("\n%.2f元的红包被抢完",sum);
    }
}

abstract class RedEnvelope {
    public double remainMoney;
    public int remainPeople;
    public double money ;
    public abstract double giveMoney();
}

class RandomRedEnvelope extends RedEnvelope {
    double minMoney;
    int integerRemainMoney;
    int randomMoney;
    Random random;
    RandomRedEnvelope(double remainMoney,int remainPeople) {
        random = new Random();
        minMoney = 0.01;
        this.remainMoney =  remainMoney;
        this.remainPeople = remainPeople;
        integerRemainMoney =(int)(remainMoney*100);
        if(integerRemainMoney<remainPeople*(int)(minMoney*100)){
            integerRemainMoney = remainPeople*(int)(minMoney*100);
            this.remainMoney =(double)integerRemainMoney;
        }
    }
    public double giveMoney() {
        if(remainPeople<=0) {
            return 0;
        }
        if(remainPeople ==1) {
            money = remainMoney;
            remainPeople--;
            return money;
        }
        randomMoney = random.nextInt(integerRemainMoney);
        if(randomMoney<(int)(minMoney*100)) {
            randomMoney = (int)(minMoney*100);
        }
        int leftOtherPeopleMoney =integerRemainMoney-randomMoney;
        int otherPeopleNeedMoney = (remainPeople-1)*(int)(minMoney*100);
        if(leftOtherPeopleMoney<otherPeopleNeedMoney) {
            randomMoney -=(otherPeopleNeedMoney-leftOtherPeopleMoney);
        }
        integerRemainMoney = integerRemainMoney - randomMoney;
        remainMoney = (double)(integerRemainMoney/100.0);
        remainPeople--;
        money = (double)(randomMoney/100.0);
        return money;
    }
}